package io.netty.example.mytest.nio.reactor;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @ClassName NioClient
 * @Description
 * @Author dukezeng
 * @CreatedTime 2019/4/13 18:05
 * @Version 1.0
 **/
public class NioClient implements Runnable {
    private String name;

    private NioClient(String name) {
        this.name = name;
    }

    @Override
    public void run() {
        SocketChannel socketChannel = null;
        try {
            socketChannel = SocketChannel.open();
            socketChannel.connect(new InetSocketAddress("127.0.0.1", NioServer.SERVER_PORT));
            ByteBuffer byteBuffer = ByteBuffer.allocate(20);
            byteBuffer.put(this.name.getBytes());
            byteBuffer.flip();

            System.out.println("client input data：" + new String(byteBuffer.array()));
            socketChannel.write(byteBuffer);

            byteBuffer.clear();
            socketChannel.read(byteBuffer);
            System.out.println("server response：" + new String(byteBuffer.array()));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (socketChannel != null) {
                try {
                    socketChannel.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        for (int i = 0 ; i < 1; i++) {
            executorService.execute(new NioClient("client " + i ));
        }
    }
}
